package week13.week_13_server;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;

public class MyCommThread extends Thread {
	Socket s;
	public MyCommThread(Socket s){
		this.s = s;
	}

	public void run(){
		try( //带资源的try
			 ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
			 ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
		){
			System.out.println("客户机连接成功！客户机地址和端口："+s.getRemoteSocketAddress());
			sendOnlineUser();
			while(true){
				try{
					Message msg=(Message)ois.readObject();
					System.out.println(msg);
					//处理注册请求，使用序列化文件存储用户
					if(msg.getMsgType()==MessageType.MSG_REG){
						User user = (User)msg.getContent();
						if(!ServerInfo.containUser(user.getUserName())){
							System.out.println("This is a new user:" + user.getUserName());
							ServerInfo.addUser(user);
							File file = new File("User/"+user.getUserName()+".ser");
							ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file));
							os.writeObject(user);
							msg.setStatus(Status.SUCCESS);
						} else {
							System.out.println("The user name:" + user.getUserName()+" has already been registered!");
							msg.setStatus(Status.FAIL);
						}
					}
					//处理登录请求
					if(msg.getMsgType()==MessageType.MSG_LOG){
						User user = (User)msg.getContent();
						if(ServerInfo.containUser(user.getUserName()) && ServerInfo.getPassword(user.getUserName()).equals(user.getPassword())){
							System.out.println("The user:" + user.getUserName()+" Login");
							msg.setStatus(Status.SUCCESS);
							ServerInfo.addOnlineUser(user.getUserName(),s);
						} else {
							System.out.println("The user name:" + user.getUserName()+" login fail");
							msg.setStatus(Status.FAIL);
						}
					}
					//转发用户发送的信息
					if (msg.getMsgType()==MessageType.MSG_TRAN){
						try {
							if (!msg.getToUser().equals("all")) {
								Socket socket = ServerInfo.getOnlineUser().get(msg.getToUser());
								ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
								os.writeObject(msg);
								os.flush();
							}else{
								sendOnlineUser(msg);
							}
							ServerInfo.getUserMap().get(msg.fromUser).addExp();
							System.out.println(((User) ServerInfo.getUserMap().get(msg.fromUser)).getExp());
							break;
						}catch (Exception ex){
							msg.setStatus(Status.FAIL);
						}
					}
					//处理发送文件保存到服务器 D://file 目录下，每个用户创建一个文件夹
					if (msg.getMsgType()==MessageType.MSG_PUT_FILE){
						try {
							saveFile(msg);
							Socket socket = ServerInfo.getOnlineUser().get(msg.getToUser());
							ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
							os.writeObject(msg);
							os.flush();
							msg.setStatus(Status.SUCCESS);
						}catch (Exception ex){
							msg.setStatus(Status.FAIL);
						}
						continue;
					}
					//返回服务器接收到发给用户的文件列表
					if (msg.getMsgType()==MessageType.MSG_LIST_FILE){
						String path= "D://file/"+msg.getFromUser()+"/";
						File dir = new File(path);
						File[] files = dir.listFiles();
						ArrayList<String> arr = new ArrayList<String>();
						for (File file:files){
							arr.add(file.getName());
						}
						msg.setContent(arr);
					}
					//客户端下载文件
					if (msg.getMsgType()==MessageType.MSG_GET_FILE){
						String path = "D://file/"+msg.getFromUser()+"/"+msg.getContent();
						File file = new File(path);
						DataOutputStream dos = new DataOutputStream(s.getOutputStream());
						FileInputStream fis = new FileInputStream(file);
						byte[] buffer = new byte[1024];
						int len = fis.read(buffer);
						while (len != -1){
							dos.write(buffer,0,len);
							dos.flush();
							len = fis.read(buffer);
						}
						System.out.println("done");
						dos.close();
						continue;
					}
					if (msg.getMsgType() == MessageType.MSG_EDITOR){
						sendOnlineUser(msg);
						break;
					}
					oos.writeObject(msg);
					oos.flush();
					System.out.println(msg);
					sendOnlineUser();
				}catch (IOException | ClassNotFoundException ex) {

				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
			System.out.println("异常信息"+ex.getMessage());
		} finally {
			//关闭套接字和流
			try {
				if (s != null)   s.close();
			} catch (IOException ex) {
				System.out.println("异常信息"+ex.getMessage());
			}
		}

	}
	//向所有的客户端发送消息
	public void sendOnlineUser(Message msg){
		for (Socket socket: ServerInfo.getOnlineUser().values()){
			try{
				ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
				os.writeObject(msg);
			}catch (Exception ex){
//				System.out.println("lsf");
			}
		}
	}
	//发送在线用户列表给所有用户
	public void sendOnlineUser(){
		HashMap onlineUser = ServerInfo.getOnlineUser();
		ArrayList<String> arr = new ArrayList();
		arr.add("all");
		for (Object key:onlineUser.keySet()){
			User user = ServerInfo.getUserMap().get(key);
			if (user == null) continue;
			arr.add(user.getUserName()+" Level "+user.getLevel());
		}
		Message msg = new Message();
		msg.setMsgType(MessageType.MSG_FLUSH);
		msg.setContent(arr);
		sendOnlineUser(msg);
	}
	//接收客户端发来的文件，存在D://file目录下
	public void saveFile(Message msg){
		try {
			DataInputStream dis = new DataInputStream(s.getInputStream());
			String path = "D://file/"+msg.getToUser()+"/";
			InputStream fis = s.getInputStream();
			File file = new File(path);
			if (!file.exists()){
				file.mkdir();
			}
			file = new File(path+msg.getContent());
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len;
			while((len = dis.read(buffer, 0, buffer.length)) != -1) {//读取
				fos.write(buffer, 0, len);
				fos.flush();
			}
			fos.close();
		}catch (Exception ex){
			ex.printStackTrace();
		}
	}
}
